var __Session = Class({
    Implements: Events,
    inited: false,
    init: function(){
        if (this.inited == true) 
            return;
        window.Xendri.JSON.addEvent('user_record', function(user){
            if (user.approved != 1) {
                $$('a#active-user').set('ajax', 'auth.logform@popup');
                Bro.log(user);
                Xendri.user = {
                    reg: 0
                };
                Xendri.Session.fireEvent('blocked');
                return;
            }
            if (user.reg == 0) { 
                $$('a#active-user').set('ajax', 'auth.logform@popup');
                Bro.log(user);
                Xendri.Session.fireEvent('fail');
            }
            else {
                $$('a#active-user').set('ajax', 'auth.helper@popup');
                Xendri.Session.fireEvent('user');
            }
            Xendri.user = user;
            Xendri.Session.updateName();
        });
        window.Xendri.JSON.addEvent('user_logout', function(user){
            if (user.reg) {
                alert('logout failed >_<');
                return;
            }
            $$('a#active-user').set('ajax', 'auth.logform@popup');
            Bro.log(user);
            Xendri.Session.fireEvent('logout');
            Xendri.closePopup();
			user.name = 'Guest';
            Xendri.user = user;
            Xendri.Session.updateName();
        });
        this.inited = true;
    },
    login: function(uname, upass, nocookie){
        this.init();
        Bro.log('doing login...');
        if (upass) 
            upass = Xendri.md5(upass);
        if (uname) 
            uname = Xendri.md5(uname);
        Xendri.JSON.send('user', 'record', {
            user: uname,
            password: upass,
            NO_COOKIE: nocookie
        });
    },
    logout: function(){
        this.init();
        Bro.log('doing logout...');
        Xendri.JSON.send('user', 'logout');
    },
    updateName: function(){
        $$('#active-user').each(function(el){
            el.innerHTML = Xendri.user.name;
        });
    }
});

window.Xendri.Session = new __Session();
